#import "NearbyModule.h"
#import "PullingRefreshTableView.h"

@interface NearbyModule () <
PullingRefreshTableViewDelegate,
UITableViewDataSource,
UITableViewDelegate
>
@property (retain,nonatomic) PullingRefreshTableView *tableView;
@property (retain,nonatomic) NSMutableArray *list;
@property (nonatomic) BOOL refreshing;
@property (assign,nonatomic) NSInteger page;
@property (assign,nonatomic) NSInteger allCnt;
@property (assign,nonatomic) NSInteger pageSize;
@property (nonatomic,assign) NSInteger gender;
@end

@implementation NearbyModule
@synthesize tableView = _tableView;
@synthesize list = _list;
@synthesize refreshing = _refreshing;
@synthesize page = _page;
@synthesize pageSize,allCnt;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row=[indexPath row];
    NSDictionary *dic=[self.list objectAtIndex:row];
        NSString* pk=[dic objectForKey:@"mp"];
        ChatViewController* ui=[[ChatViewController alloc] initWithChatter:pk isGroup:NO];
    ui.title=[dic objectForKey:@"nickname"];
    ui.hidesBottomBarWhenPushed=YES;
    
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];
    NSString * locationString=[dateformatter stringFromDate:senddate];
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    [accountDefaults setObject:locationString forKey:[NSString stringWithFormat:@"hx-%@",pk]];
    //NSString * morelocationString=[dateformatter stringFromDate:senddate];
    
        [self.navigationController pushViewController:ui animated:NO];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView launchRefreshing];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 87.0 ;
}

- (void)loadView
{
    [super loadView];
    _list = [[NSMutableArray alloc] init ];
    CGRect frame;
    float iosVersion=[[[UIDevice currentDevice] systemVersion] floatValue];
    
    int h=[Tools getScreenHeight];
    
    
    
    _tableView = [[PullingRefreshTableView alloc] initWithFrame:CGRectMake(0,0, 320, h-65) pullingDelegate:self];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [self.view addSubview:_tableView];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.pageSize=10;
    
    
    
    
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 110, 0);
    self.view.backgroundColor=[UIColor whiteColor];
    
    
    gender=1;
    
    
    
    
    locationManager = [[CLLocationManager alloc] init];
    
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = 100.0f;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        NSLog(@"requestAlwaysAuthorization....");
        [locationManager requestWhenInUseAuthorization];
        [locationManager startUpdatingLocation];
    }else{
        [locationManager startUpdatingLocation];
    }
    
    UIButton*  boyBtn=[[UIButton  alloc] initWithFrame:CGRectMake(0, 0, 80, 44)];
//    UILabel*  boyLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 12,80, 20)];
//    boyLb.textColor=[UIColor redColor];
//    boyLb.text=@"男";
//    boyLb.textAlignment=NSTextAlignmentCenter;
//    [boyBtn addSubview:boyLb];
    [boyBtn setTitle:@"男" forState:UIControlStateNormal];
    [boyBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [boyBtn addTarget:self action:@selector(genderSwitch:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    UIButton*  girlBtn=[[UIButton  alloc] initWithFrame:CGRectMake(80, 0, 80, 44)];
    
//    UILabel*  girlLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 12,80, 20)];
//    girlLb.textColor=[UIColor whiteColor];
//    girlLb.text=@"女";
//    girlLb.textAlignment=NSTextAlignmentCenter;
//    [girlBtn addSubview:girlLb];
    [girlBtn setTitle:@"女" forState:UIControlStateNormal];
    [girlBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [girlBtn addTarget:self action:@selector(genderSwitch:) forControlEvents:UIControlEventTouchUpInside];
    
    boyBtn.tag = 99;
    girlBtn.tag = 100;
    
    UIView* v=[[UIView  alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
    [v addSubview:boyBtn];
    [v addSubview:girlBtn];
    
    
    self.navigationItem.titleView=v;
    [self.tableView setBackgroundView:nil];
    gender = 1;
    
}


-(void)genderSwitch:(UIButton *)sender{
    [sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    if (sender.tag == 99) {
        UIButton *btn = [self.navigationItem.titleView viewWithTag:100];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        gender = 1;
    }else{
        UIButton *btn = [self.navigationItem.titleView viewWithTag:99];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        gender = 2;
    }
    [self.tableView launchRefreshing];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // 获取经纬度
    NSLog(@"纬度:%f",newLocation.coordinate.latitude);
    NSLog(@"经度:%f",newLocation.coordinate.longitude);
    // 停止位置更新
    [manager stopUpdatingLocation];
    longitude=newLocation.coordinate.longitude;
    latitude=newLocation.coordinate.latitude;
    if (self.page == 0) {
        
        [self.tableView launchRefreshing];
    }
    
}

// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}
-(void)clickOnBackBut{
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)loadData{
    self.page++;
    if (self.refreshing) {
        self.page = 0;
        self.refreshing = NO;
        [self.list removeAllObjects];
    }
    
    
    
    
    NSString *url=@"";
    url=[HOST stringByAppendingString:@"index.php/appUser/findNearByUserList?currentPage="];
    NSMutableString *mUrl=[[NSMutableString alloc] initWithString:url];
    NSString  *sCurrentPage=[NSString stringWithFormat:@"%d",self.page];
    [mUrl appendString:sCurrentPage];
    [mUrl appendString:@"&longi="];
    
    [mUrl appendString:[NSString stringWithFormat:@"%f",longitude]];
    //
    [mUrl appendString:@"&lanti="];
    
    [mUrl appendString:[NSString stringWithFormat:@"%f",latitude]];
    [mUrl appendString:@"&flag=1"];
    
    
    
    
    NSLog(@"murl===%@",mUrl);
    
    
    NSError *error;
    NSString *jsonStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:mUrl] encoding:NSUTF8StringEncoding error:&error];
    NSLog(@"jsonStr===%@",jsonStr);
    
    NSDictionary* tmpDic=[NSDictionary dictionaryWithDictionary:[jsonStr JSONValue]];
    
    NSString* _allCnt=[tmpDic objectForKey:@"size"];
    self.allCnt=[_allCnt intValue];
    NSMutableArray *infoList=[tmpDic objectForKey:@"list"];
    
    for(int i = 0 ; i< [infoList count];i++){
        [self.list addObject: [infoList objectAtIndex:i]];
    }
    
//    int i = 0;
    NSArray * array = [NSArray arrayWithArray: self.list];
    for (NSDictionary *dic in array) {
        if (![[dic objectForKey:@"gender"]isEqualToString:[NSString stringWithFormat:@"%ld",(long)gender]]) {
//            [self.list removeObjectAtIndex:i];
//            i--;
            [self.list removeObject:dic];
        }
//        i++;
    }
    [self performSelectorOnMainThread:@selector(didFinishRequest) withObject:nil waitUntilDone:YES];
    
    
    
}
-(void)didFinishRequest{
    NSLog(@"%d====",self.list.count);
    if (self.list.count>=self.allCnt) {
        if (self.allCnt<=self.pageSize) {
            [self.tableView tableViewDidFinishedLoading];
            self.tableView.reachedTheEnd  = YES;
            [self.tableView reloadData];
        }
        if (self.allCnt==self.list.count) {
            [self.tableView tableViewDidFinishedLoading];
            self.tableView.reachedTheEnd  = YES;
            [self.tableView reloadData];
        }
        self.tableView.reachedTheEnd  = YES;
        
    } else {
        [self.tableView tableViewDidFinishedLoading];
        self.tableView.reachedTheEnd  = NO;
        [self.tableView reloadData];
    }
    
}

#pragma mark - TableView*
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"_CELL";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;
    }
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            [subview removeFromSuperview];
        }
        if ([subview isKindOfClass:[UIButton class]]) {
            [subview removeFromSuperview];
        }
        if ([subview isKindOfClass:[UIImageView class]]) {
            [subview removeFromSuperview];
        }
        
    }
    
    NSUInteger row=indexPath.row;
    if (row<self.list.count) {
        NSDictionary* dic=[self.list objectAtIndex:row];
        UIImageView* avatarImgView=[[UIImageView alloc] initWithFrame:CGRectMake(4+2,4+2, 68-4, 80-4-4)];
        NSString* avatar=[dic objectForKey:@"avatar"];
        if (![Tools isBlankString:avatar]&&[avatar length]>5) {
            
            
            if (avatar && [avatar rangeOfString:@"http"].location != NSNotFound) {
                [avatarImgView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",avatar]] placeholderImage:[UIImage new]];
            }else{
                avatar=[HOST stringByAppendingString:avatar];
                NSLog(@"用户头像=%@",avatar);
                NSURL* avatarURL=[NSURL URLWithString:avatar];
                [avatarImgView setImageWithURL:avatarURL placeholderImage:[UIImage imageNamed:@"empty_photo"]];
            }
            [cell.contentView addSubview:avatarImgView];
            
//            avatar=[HOST stringByAppendingString:avatar];
//            NSLog(@"司机头像=%@",avatar);
//            NSURL* avatarURL=[NSURL URLWithString:avatar];
//            [avatarImgView sd_setImageWithURL:avatarURL placeholderImage:[UIImage imageNamed:@"empty_photo"]];
//            //[avatarImgView setImageWithURL:avatarURL placeholderImage:[UIImage imageNamed:@"empty_photo"]];
//            
//            
//            //setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
//            
//            
//            [cell.contentView addSubview:avatarImgView];
        }else{
            avatarImgView.image=[UIImage imageNamed:@"empty_photo"];
            [cell.contentView addSubview:avatarImgView];
        }
        
        
        int x=15;
        //标题
        NSString* name=[dic objectForKey:@"nickname"];
        
        UILabel* titleLB=[[UILabel alloc] initWithFrame:CGRectMake(68+x/2, 6, 240, 22)];
        
        titleLB.text=name;
        titleLB.font=[UIFont boldSystemFontOfSize:14];
        titleLB.textColor=[UIColor blackColor];
        titleLB.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:titleLB];
        
        //////////////////
        NSString* price=[dic objectForKey:@"qm"];
        
        UILabel* priceLB=[[UILabel alloc] initWithFrame:CGRectMake(68+x/2,40, 120, 22)];
        if (price.length==0) {
            
            priceLB.text=@"这人太懒什么都没有写";
        }else{
            priceLB.text=[NSString stringWithFormat:@"%@",price];
        }
        
        
        
        priceLB.font=[UIFont systemFontOfSize:12];
        priceLB.textColor=[UIColor darkGrayColor];
        priceLB.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:priceLB];
        ////////
        
        
        //

        //NSString* juli=[dic objectForKey:@"juli"];
        UILabel* juliLB=[[UILabel alloc] initWithFrame:CGRectMake(x+68+150, 22, 210, 22)];
        
        //juliLB.text=[NSString stringWithFormat:@"%@",juli];
        juliLB.font=[UIFont systemFontOfSize:12];
        juliLB.textColor=[UIColor grayColor];
        
        
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSString *str = [accountDefaults objectForKey:[NSString stringWithFormat:@"hx-%@",[dic objectForKey:@"mp"]]];
        NSLog(@"%@ str:%@",[NSString stringWithFormat:@"hx-%@",[dic objectForKey:@"mp"]],str);
        if (str.length!=0) {
            juliLB.text = str;
        }else{
            juliLB.text = @"";
        }
        
        juliLB.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:juliLB];
        
        
        ////
        NSString* add_time=[dic objectForKey:@"activity_time"];
        UILabel* add_timeLB=[[UILabel alloc] initWithFrame:CGRectMake(x+68+150, 50, 210, 22)];
        
        add_timeLB.text=add_time;
        add_timeLB.font=[UIFont systemFontOfSize:12];
        add_timeLB.textColor=[UIColor grayColor];
        
        
        
        add_timeLB.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:add_timeLB];
        
        
        
        
        UIImage* arrowImg=[UIImage imageNamed:@"arrow"];
        UIImageView*  arrowImgView=[[UIImageView alloc] initWithFrame:CGRectMake(290, 40, 12*0.9, 21*0.9)];
        arrowImgView.image=arrowImg;
        [cell.contentView addSubview:arrowImgView];
        
        
        //        UIImage* henxian=[UIImage imageNamed:@"凹线条640.png"];
        //        UIImageView *henxianView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)];
        //        henxianView.image=henxian;
        //        [cell.contentView addSubview:henxianView];
        
        
        
    }
    
    return cell;
}

#pragma mark - PullingRefreshTableViewDelegate
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView{
    self.refreshing = YES;
    [self performSelector:@selector(loadData) withObject:nil afterDelay:0.1];
}

- (NSDate *)pullingTableViewRefreshingFinishedDate{
    NSDateFormatter *df = [[NSDateFormatter alloc] init ];
    df.dateFormat = @"yyyy-MM-dd HH:mm";
    NSDate * date = [NSDate date];//获取当前的时间
    NSString *MyHitOrderListUIStr= [df stringFromDate:date];
    date = [df dateFromString:MyHitOrderListUIStr];
    return date;
}

- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView{
    [self performSelector:@selector(loadData) withObject:nil afterDelay:0.1f];
}

#pragma mark - Scroll

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.tableView tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.tableView tableViewDidEndDragging:scrollView];
}

@end
